/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package publicmethod;

import com.jacob.activeX.*;
import com.jacob.com.*;
import junchangmis.codecSetting.*;

/**
 *
 * @author developers
 */
public class WordService {

    private static final long serialVersionUID = -1L;
    public ActiveXComponent MsWordApp = null;
    private Dispatch document = null;
    ///自定义参数
    String name;
    String classCode;

    public WordService(String name, String classCode) {
        this.name = name;
        this.classCode = classCode;
    }

    public void openWord(boolean makeVisible) {
        //Open Word if we\'ve not done it already
        if (MsWordApp == null) {
            MsWordApp = new ActiveXComponent("Word.Application");
        }
        //Set the visible property as required.
        Dispatch.put(MsWordApp, "Visible",
                new Variant(makeVisible));
    }

    /**
     * 打开已知的word文档
     * @param markVisible 可视化状态
     * @param docPath 文档路径
     */
    public void openWord(boolean markVisible, final String docPath) {
        if (MsWordApp == null) {
            MsWordApp = new ActiveXComponent("Word.Application");
        }
        //Set the visible property as required.
        Dispatch.put(MsWordApp, "Visible", new Variant(markVisible));
        Dispatch docs = MsWordApp.getProperty("Documents").toDispatch();
        document = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[]{docPath}, new int[1]).toDispatch();
    }

    /**
     * 创建Word文档
     *
     */
    public void createNewDocument() {
        //Find the Documents collection object maintained by Word
        Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
        //Call the Add method of the Documents collection to create
        //a new document to edit
        document = Dispatch.call(documents, "Add").toDispatch();
    }

    /**
     * 插入文本
     * @param textToInsert
     */
    public void insertText(String textToInsert) {
        // Get the current selection within Word at the moment. If
        // a new document has just been created then this will be at
        // the top of the new doc
        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
        //Put the specified text at the insertion point
        Dispatch.put(selection, "Text", textToInsert);
    }

    public void saveFileAs(String filename) {
        Dispatch.call(document, "SaveAs", filename);
    }

    public void printFile() {
        //Just print the current document to the default printer
        Dispatch.call(document, "PrintOut");
    }

    /**
     * 查找替换文本
     * @param searchText 需要查找的关键字
     * @param replaceText 要替换成的关键字
     */
    public void searchReplace(final String s1, final String r1) {
        Dispatch selection = MsWordApp.getProperty("Selection").toDispatch();
        Dispatch find = ActiveXComponent.call(selection, "Find").toDispatch();
        //查找什么文本
        Dispatch.put(find, "Text", s1);
        //替换文本
        Dispatch.call(find, "ClearFormatting");
        Dispatch.put(find, "Text", s1);
        Dispatch.call(find, "Execute");
        Dispatch.put(selection, "Text", r1);
    }

    /**
     * 把指定的值设置到指定的标签中去
     * @param bookMarkKey
     */
    public void setBookMark(final String bookMarkKey, final String bookMarkValue) {
        Dispatch activeDocument = MsWordApp.getProperty("ActiveDocument").toDispatch();
        Dispatch bookMarks = ActiveXComponent.call(activeDocument, "Bookmarks").toDispatch();
        boolean bookMarkExist1 = Dispatch.call(bookMarks, "Exists", bookMarkKey).getBoolean();
        if (bookMarkExist1 == true) {
            Dispatch rangeItem = Dispatch.call(bookMarks, "Item", bookMarkKey).toDispatch();
            Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
            //取标签的值
            //String bookMarkValue=Dispatch.get(range,"Text").toString();
            //bookMarkValue="test";
            if (bookMarkValue != null) {
                Dispatch.put(range, "Text", new Variant(bookMarkValue));
            }
        } else {
            System.out.println("not exists bookmark!");
        }
    }

    /**
     * 保存Word文档到指定的目录(包括文件名)
     * @param filePath
     */
    public void saveWordFile(final String filePath) {
        //保存文件
        Dispatch.invoke(document, "SaveAs", Dispatch.Method, new Object[]{filePath, new Variant(0)}, new int[1]);
        //作为word格式保存到目标文件
        Variant f = new Variant(false);
        Dispatch.call(document, "Close", f);
    }

    public void closeDocument() {
        // Close the document without saving changes
        // 0 = wdDoNotSaveChanges
        // -1 = wdSaveChanges
        // -2 = wdPromptToSaveChanges
        Dispatch.call(document, "Close", new Variant(0));
        document = null;
    }

    public void closeWord() {
        Dispatch.call(MsWordApp, "Quit");
        MsWordApp = null;
        document = null;
    }

    public void generateDoc() {
        openWord(true, PrintTest.getPath() + "\\getFee.doc");
        searchReplace("name", name);
        saveWordFile(PrintTest.getPath() + "\\催费通知单\\" + name + ".doc");

        openWord(true, PrintTest.getPath() + "\\催费通知单\\" + name + ".doc");
        searchReplace("code", classCode);
        saveWordFile(PrintTest.getPath() + "\\催费通知单\\" + name + ".doc");

        openWord(true, PrintTest.getPath() + "\\催费通知单\\" + name + ".doc");
        searchReplace("title", codecMethodNew.getMeaning(classCode));
        saveWordFile(PrintTest.getPath() + "\\催费通知单\\" + name + ".doc");

        closeWord();
    }

    public static void main(String[] args) {
        /*WordService word = new WordService();

        word.openWord(true, PrintTest.getPath() + "\\getFee.doc");
        word.searchReplace("name", "樊骏");
        word.saveWordFile(PrintTest.getPath() + "\\催费通知单\\getFee.doc");

        word.openWord(true, PrintTest.getPath() + "\\催费通知单\\getFee.doc");
        word.searchReplace("code", "SSY");
        word.saveWordFile(PrintTest.getPath() + "\\催费通知单\\getFee.doc");

        word.openWord(true, PrintTest.getPath() + "\\催费通知单\\getFee.doc");
        word.searchReplace("title", "美术");
        word.saveWordFile(PrintTest.getPath() + "\\催费通知单\\getFee.doc");

        word.closeWord();*/
    }
}
